<?php

namespace app\admin\controller;

use app\admin\controller\Dbfimport;

use app\admin\service\ArticleService;
use app\admin\service\VllmService;
use Everyman\Neo4j\Command\AddStatementsToTransaction;
use think\Db;
use app\common\helper\MyHelper;
use Elasticsearch\ClientBuilder;
use app\api\controller\Indexsystem;
use app\admin\service\OllamaService;


class Article
{


    function attributeInformation()
    {
        $data = request()->put();

        $resultProject = Db::table("zstp_project")->where(array("id" => $data ['project_id']))->find();
        $graphDatabase = $resultProject ['graph_database'];

        $cypher = "MATCH (n {id: '" . $data['id'] . "'}) RETURN n";

        $data = neo4j_connect_entity($cypher, $graphDatabase);

        $data = json_decode($data, true);

        if (empty($data['results'])) {
            return json(array('code' => 200, "data" => array(), 'message' => '图数据库中未找到相关内容'));
        }


        $list[0]['zd'] = "id";
        $list[0]['value'] = $data['results'][0]['data'][0]['row'][0]['id'];

        $list[1]['zd'] = "name";
        $list[1]['value'] = $data['results'][0]['data'][0]['row'][0]['name'];

        $list[2]['zd'] = "desc";
        $list[2]['value'] = "";
        if (!empty($data['results'][0]['data'][0]['row'][0]['desc'])) {
            $list[2]['value'] = $data['results'][0]['data'][0]['row'][0]['desc'];
        }


        $list[3]['zd'] = "semanticType";
        $list[3]['value'] = "";
        if (!empty($data['results'][0]['data'][0]['row'][0]['semanticType'])) {
            $list[3]['value'] = $data['results'][0]['data'][0]['row'][0]['semanticType'];
        }


        $list[4]['zd'] = "_name_vector";
        $list[4]['value'] = "";
        if (!empty($data['results'][0]['data'][0]['row'][0]['_name_vector'])) {
            $list[4]['value'] = json_encode($data['results'][0]['data'][0]['row'][0]['_name_vector'], JSON_UNESCAPED_UNICODE);
        }


        return json(array('code' => 200, "data" => $list, 'message' => ''));


    }

    function institutionalevents()
    {
        $data = request()->put();

        $resultProject = Db::table("zstp_project")->where(array("id" => $data ['project_id']))->find();
        $graphDatabase = $resultProject ['graph_database'];

        if (empty($data['name'])) {
            return json(array('code' => 400, 'message' => '请输入要查询的组织名称'));
        }

        $cypher = "MATCH (anyNode)-[r]-(related) WHERE anyNode.name =~ '.*" . $data['name'] . ".*' AND (related:`" . $graphDatabase . ".Event` OR related:`" . $graphDatabase . ".Others`) OPTIONAL MATCH (related)-[sourceRel:source]->(sourceEntity) RETURN DISTINCT anyNode.name AS nodeName, type(r) AS relationType, related.name AS relatedName, sourceEntity.name AS sourceName";


        $data = neo4j_connect_entity($cypher, $graphDatabase);

        $data = json_decode($data, true);

//        var_dump(11);

        if (empty($data['results'])) {
            return json(array('code' => 200, "data" => array(), 'message' => '图数据库中未找到相关内容'));
        }

        $data = $data['results'];
        $data = $data[0]['data'];


        $arrTime = array();

        $jlData = array();

        foreach ($data as $key => $value) {

            if (empty($value['row'][3])) {
                continue;
            }
            $title = $value['row'][3];
            $titleArr = explode("-", $title);
            if (empty($titleArr[3])) {
                continue;
            }
            $pattern = '/\d+/';

            $year = "";

            if (preg_match($pattern, $titleArr[3], $matches)) {
                $year = $matches[0];  // 输出: 1955
            };


            $bj = $value['row']['1'] . $value['row']['2'];

            if (empty($jlData[$year]) || !in_array($bj, $jlData[$year])) {
                $arrTime[(int)$year][] = $value['row'];
            }

            $jlData[$year][] = $bj;


        }


//        krsort($arrTime);


        return json(array('code' => 200, "data" => $arrTime, 'message' => ''));


    }


    function raceability()
    {
        $data = request()->put();


        $resultProject = Db::table("zstp_project")->where(array("id" => $data ['project_id']))->find();
        $graphDatabase = $resultProject ['graph_database'];


        //溯源文档
        $cypher = "MATCH (startNode {name: '" . $data['name'] . "'})-[:source]->(endNode) RETURN  endNode.name,endNode.id";


        $data = neo4j_connect_entity($cypher, $graphDatabase);

        $data = json_decode($data, true);

//        var_dump($data);

        if (empty($data['results'])) {
            return json(array('code' => 200, "data" => array(), 'message' => '图数据库中未找到相关内容'));
        }

        $data = $data['results'];
        $data = $data[0]['data'];

        $dhArr = array();
        foreach ($data as $key => $value) {
            $dhArr[] = $value['row'][0];
        }
        $map["dh"] = array("in", $dhArr);
        $result = Db::table("zstp_article")->where($map)->field("id,dh")->select();
        $list = array();
        foreach ($result as $key => $value) {
            $list[] = $value;
        }

        return json(array('code' => 200, "data" => $list, 'message' => ''));

    }


    function getEntityJson()
    {

        $data = request()->put();
        if (!isset($data['project_id']) || empty($data['project_id'])) {
            if (empty($data['name'])) {
                $data['name'] = $data['dh'];
            }
            $resultQzh = Db::table("zstp_article")->field("qzh")->where(array("dh" => $data['name']))->find();
            $projectData = Db::table("zstp_project")->where(array("qzh" => $resultQzh['qzh']))->find();
            $data['project_id'] = $projectData['id'];
        }


        $project_id = $data['project_id'];

        $resultProject = Db::table("zstp_project")->where(array("id" => $data['project_id']))->find();

        $graphDatabase = $resultProject ['graph_database'];

        $resultdh = array();

        if (empty($data['type'])) {
            if (empty($data['name'])) {
                return json(array('code' => 400, 'message' => '请输入要查询的实体名称'));
            }
            $radio2 = $data['radio2'];

            if ($radio2 == '一度关系') {
                $cypher = "MATCH (n)-[r]-(m) WHERE n.name=~'.*" . $data['name'] . ".*' UNWIND r AS rel RETURN DISTINCT type(rel),startNode(rel).name, endNode(rel).name, labels(startNode(rel))[0], endNode(rel).id,labels(endNode(rel))[0],startNode(rel).id limit 500";

            } else {
                //模糊查询
                $cypher = "MATCH (n)-[r*1..2]-(m) WHERE n.name=~'.*" . $data['name'] . ".*' UNWIND r AS rel RETURN DISTINCT type(rel),startNode(rel).name, endNode(rel).name, labels(startNode(rel))[0], endNode(rel).id,labels(endNode(rel))[0],startNode(rel).id limit 5000";

            }


        } else {

            $radio1 = $data['radio1'];

            if ($radio1 == '一度关系') {
                $cypher = "MATCH (n)-[r]-(m) WHERE n.name = '" . $data['dh'] . "' RETURN DISTINCT type(r) AS relationshipType, startNode(r).name AS startNodeName, endNode(r).name AS endNodeName, labels(startNode(r))[0] AS startNodeLabel, endNode(r).id AS endNodeId, labels(endNode(r))[0] AS endNodeLabel, startNode(r).id AS startNodeId LIMIT 500";
            } else {
                $cypher = "MATCH (n)-[r*1..2]-(m) WHERE n.name ='" . $data['dh'] . "' UNWIND r AS rel RETURN DISTINCT       type(rel),startNode(rel).name, endNode(rel).name, labels(startNode(rel))[0], endNode(rel).id,labels(endNode(rel))[0],startNode(rel).id limit 500";
            }

            $mapdh['dh'] = $data['dh'];
            $resultdh = Db::table("zstp_article")->field("dh,content,id")->where($mapdh)->find();

        }


//        var_dump($cypher);


        $data = neo4j_connect_entity($cypher, $graphDatabase);
        $data = json_decode($data, true);


        if (empty($data['results'])) {
            return json(array('code' => 200, "data" => array(), 'message' => '图数据库中未找到相关内容'));
        }


        $data = $data['results'];
        $data = $data[0]['data'];


        if (empty($data)) {
            return json(array('code' => 200, "data" => array(), 'message' => '没有找到相关图谱内容'));
        }

        $eData = array();
        $categories = array();
        $links = array();
        $category = array();

        $shiti = array();
        $qiu = array();
        foreach ($data as $key => $value) {


            $cate = $value["row"][0];


            if ($cate == "OfficialName") {
                $cate = "别名";
            }

            if ($cate == "source") {
                $cate = "溯源";
            }


            $category[] = $cate;

            $categories[] = array("name" => $cate);

            $links[] = array(
                "category" => $cate,
                "target" => $value["row"][1],
                "source" => $value["row"][2],

            );


//            var_dump($value["row"]);

            $startTyoe = $value['row']["3"];

            $startDataType = explode(".", $startTyoe);

            $endTyoe = $value['row']["5"];

            $endDataType = explode(".", $endTyoe);


            $t1 = $value["row"]["1"];
            $t2 = $value["row"]["2"];

            $strStart = $t1 . $startDataType[0];

            $strEnd = $t2 . $endDataType[0];


            if (!in_array($strStart, $qiu)) {


                $nodeInfo['id'] = $value["row"][6];
                $nodeInfo['name'] = $t1;
                $nodeInfo['type'] = $value["row"][3];

                $qar = array("name" => $t1, "category" => $cate, "nodeInfo" => $nodeInfo, "itemStyle" => array("color" => "#000", " borderColor" => "red", "borderWidth" => 10), "draggable" => true, "symbolSize" => array(30, 30), "itemStyle" => array("color" => getRandomColorName(), "borderColor" => "#000000", "borderWidth" => 1));
                $qiu [] = $strStart;

                if (empty($startDataType[1])) {
                    continue;
                }

                if ($startDataType[1] == "Person") {
                    $qar['itemStyle']['color'] = "#fac455";
                    $qar["symbol"] = getUserSvg();
                }

                if ($startDataType[1] == "Organization") {

                    $qar['itemStyle']['color'] = "#f26667";


                    $qar["symbol"] = getShopSvg();
                }

                if ($startDataType[1] == "Chunk") {
                    $qar['itemStyle']['color'] = "#4c8eda";

                    $qar["symbol"] = getOrderSvg();
                }
                if ($startDataType[1] == "Event") {
                    $qar['itemStyle']['color'] = "#8dcc93";
                    $qar["symbol"] = getFlagSvg();
                }
                if ($startDataType[1] == "Others") {
                    $qar['itemStyle']['color'] = "#57c7e3";
                }
                if ($startDataType[1] == "Date") {
                    $qar['itemStyle']['color'] = "#edb6c9";
                    $qar["symbol"] = getDateSvg();
                }
                if ($startDataType[1] == "GeographicLocation") {
                    $qar['itemStyle']['color'] = "#569480";
                    $qar["symbol"] = getGeographicLocationSvg();
                }
                $eData[] = $qar;

            }


            if (!in_array($strEnd, $qiu)) {


                $nodeInfo['id'] = $value["row"][4];
                $nodeInfo['name'] = $t2;
                $nodeInfo['type'] = $value["row"][5];

                $qar = array("name" => $t2, "category" => $cate, "nodeInfo" => $nodeInfo, "itemStyle" => array("color" => "#000", " borderColor" => "red", "borderWidth" => 10), "draggable" => true, "symbolSize" => array(30, 30), "itemStyle" => array("color" => getRandomColorName(), "borderColor" => "#000000", "borderWidth" => 1));
                $qiu [] = $strEnd;

                $endTyoe = $value['row']["5"];


                $endDataType = explode(".", $endTyoe);

                if (empty($startDataType[1])) {
                    continue;
                }


                if ($endDataType[1] == "Person") {

                    $qar['itemStyle']['color'] = "#fac455";
                    $qar["symbol"] = getUserSvg();
                }

                if ($endDataType[1] == "Organization") {
                    $qar['itemStyle']['color'] = "#f26667";
                    $qar["symbol"] = getShopSvg();
                }

                if ($endDataType[1] == "Chunk") {
                    $qar['itemStyle']['color'] = "#4c8eda";
                    $qar["symbol"] = getOrderSvg();
                }
                if ($endDataType[1] == "Event") {
                    $qar['itemStyle']['color'] = "#8dcc93";
                    $qar["symbol"] = getFlagSvg();
                }

                if ($endDataType[1] == "Others") {
                    $qar['itemStyle']['color'] = "#57c7e3";

                }

                if ($endDataType[1] == "Date") {
                    $qar['itemStyle']['color'] = "#edb6c9";
                    $qar["symbol"] = getDateSvg();
                }

                if ($endDataType[1] == "GeographicLocation") {
                    $qar['itemStyle']['color'] = "#569480";
                    $qar["symbol"] = getGeographicLocationSvg();
                }


                $eData[] = $qar;

            }


        }


        $category = array_unique($category);
        $categories = array_map(function ($name) {
            return ['name' => $name];
        }, $category);

        $categories = array_values($categories);


        $result['data'] = $eData;
        $result['links'] = $links;
        $result['category'] = $categories;


        $result['cate'] = array_slice(array_values($category), 0, 50);

        return json(array('code' => 200, "data" => $result, "project_id" => $project_id, 'message' => '', "dh" => $resultdh));


    }

    function getNeoJson()
    {


        $data = request()->put();


        $data = neo4j_connect($data['dh']);

        $data = json_decode($data, true);


//        var_dump(   $data );


        $data = $data['results'];
        $data = $data[0]['data'];

        if (empty($data)) {
            return json(array('code' => 400, "data" => array(), 'message' => '暂无数据'));
        }

        $eData = array();
        $categories = array();
        $links = array();
        $category = array();

        $qiu = array();
        foreach ($data as $key => $value) {

//            var_dump($value);
            $t1 = $value["row"][1];
            $t2 = $value["row"][2];
            if (!in_array($t1, $qiu)) {
                $qiu [] = $t1;
                $qiuArr[] = array("name" => $t1, "category" => $value['row']['0']);
            }
            if (!in_array($t2, $qiu)) {
                $qiu [] = $t2;
                $qiuArr[] = array("name" => $t2, "category" => $value['row']['0']);
            }

            $categories[] = array("name" => $value["row"][0]);
            $links[] = array(
                "target" => $value["row"][1],
                "source" => $value["row"][2],
                "category" => $value["row"][0],
            );

        }


        foreach ($qiuArr as $key => $value) {

            $eData[] = array("name" => $value['name'], "itemStyle" => array("color" => "#000"), "draggable" => true, "symbolSize" => array(30, 30), "itemStyle" => array("color" => getRandomColorName()), "category" => $value['category'], " borderColor" => "#000", "borderWidth" => 10);
        }


        //去重
        foreach ($categories as $key => $value) {
            $category[] = $value["name"];
        }
        $category = array_unique($category);
        $categories = array_map(function ($name) {
            return ['name' => $name];
        }, $category);

        $categories = array_values($categories);


        $result['data'] = $eData;

        $result['links'] = $links;

        $result['category'] = $categories;

        return json(array('code' => 200, "data" => $result, 'message' => ''));

    }


    function getArticleByid()
    {

        $data = request()->put();

        if (empty($data['id'])) {
            return json(array('code' => 400, 'message' => '请输入预览档案id'));
        }

        $id = $data['id'];

        $result = MyHelper::getArticleInfoById($data['id']);




        $serverIp = config("kgFilePath");
        $id = $data['id'];
        $str = md5($id);
        $url = $serverIp . "/pdf/data/{$id}/" . "{$str}_monolayer.pdf";;


        $result['data']['pdf_url'] = $url;


        if (empty($result)) {
            return json(array('code' => 400, "data" => array(), 'message' => '请输入预览档案id'));
        } else {
            return json(array('code' => 200, "data" => $result['data'], 'message' => '请输入预览档案id'));
        }
    }


    function getArticleByidabutBiaoyin()
    {


        $data = request()->put();

        if (empty($data['id'])) {
            //没有id找出id
            $mapb['audit_status'] = array("=", 0);
            $data = Db::table('zstp_article')->order('id asc')->where($mapb)->find();
            $data = 0;
            if (empty($data)) {
                return json(array('code' => 200, "data" => array(), 'message' => ''));
            }
        }

        $id = $data['id'];

        $result = MyHelper::getArticleInfoByIdAbutBiaoyin($data['id']);

        $resultzrdhh = MyHelper::getArticleInfoById($data['id']);

        $result['data']['contentzrdhh'] = $resultzrdhh['data']['content'];


        $serverIp = config("kgFilePath");


        $id = $data['id'];
        $str = md5($id);
        $url = $serverIp . "/pdf/data/{$id}/" . "{$str}_monolayer.pdf";;

        $result['data']['pdf_url'] = $url;


        //计算载体数量

        $Dbfimport = new Dbfimport();
        $jsonPath = $Dbfimport->getUniqueString($id, 3);
        $jsonData = file_get_contents($jsonPath);

        $result['data']['ztsl'] = null;


        //唯一标识
        $xml = '<?xml version="1.0" encoding="UTF-8"?><Root>';

        //档号
        $row = '<row SourceFieldName="dh" NewFieldName="档号" value="' . $result['data']['dh'] . '"></row>';

        $xml = $xml . $row;
        //主题词
        $row = '<row SourceFieldName="ztc" NewFieldName="主题词" value="' . $result['data']['ztc'] . '"></row>';

        $xml = $xml . $row;
        //密级
        $row = '<row SourceFieldName="mj" NewFieldName="密级" value="' . $result['data']['mj'] . '"></row>';
        $xml = $xml . $row;
        //保管期限
        $row = '<row SourceFieldName="bgqx" NewFieldName="保管期限" value="' . $result['data']['bgqx'] . '"></row>';
        $xml = $xml . $row;
        //全宗号
        $row = '<row SourceFieldName="qzh" NewFieldName="全宗号" value="' . $result['data']['qzh'] . '"></row>';
        $xml = $xml . $row;
        //分类号
        $row = '<row SourceFieldName="flh" NewFieldName="分类号" value="' . $result['data']['flh'] . '"></row>';
        $xml = $xml . $row;
        //案卷号
        $row = '<row SourceFieldName="ajh" NewFieldName="案卷号" value="' . $result['data']['ajh'] . '"></row>';
        $xml = $xml . $row;
        //件号
        $row = '<row SourceFieldName="jh" NewFieldName="件号" value="' . $result['data']['jh'] . '"></row>';
        $xml = $xml . $row;
        //关键词
        $row = '<row SourceFieldName="gjc" NewFieldName="关键词" value="' . $result['data']['gjc'] . '"></row>';
        $xml = $xml . $row;
        //类别号
        $row = '<row SourceFieldName="lbh" NewFieldName="类别号" value="' . $result['data']['lbh'] . '"></row>';
        $xml = $xml . $row;
        //文种
        $row = '<row SourceFieldName="wz" NewFieldName="文种" value="' . $result['data']['wz'] . '"></row>';
        $xml = $xml . $row;
        //时间
        $row = '<row SourceFieldName="sj" NewFieldName="时间" value="' . $result['data']['sj'] . '"></row>';
        $xml = $xml . $row;
        //题名
        $row = '<row SourceFieldName="tm" NewFieldName="题名" value="' . $result['data']['tm'] . '"></row>';
        $xml = $xml . $row;
        //文件编号
        $row = '<row SourceFieldName="wjbh" NewFieldName="文件编号" value="' . $result['data']['wjbh'] . '"></row>';
        $xml = $xml . $row;
        //载体类型
        $row = '<row SourceFieldName="ztlx" NewFieldName="载体类型" value="' . $result['data']['ztlx'] . '"></row>';
        $xml = $xml . $row;
        //载体数量
        $row = '<row SourceFieldName="ztsl" NewFieldName="载体数量" value="' . $result['data']['ztsl'] . '"></row>';
        $xml = $xml . $row;
        //载体单位
        $row = '<row SourceFieldName="ztdw" NewFieldName="载体单位" value="' . $result['data']['ztdw'] . '"></row>';
        $xml = $xml . $row;
        //载体规格
        $row = '<row SourceFieldName="ztgg" NewFieldName="载体规格" value="' . $result['data']['ztgg'] . '"></row>';
        $xml = $xml . $row;
        //责任者
        $row = '<row SourceFieldName="zrz" NewFieldName="责任者" value="' . $result['data']['zrz'] . '"></row>';
        $xml = $xml . $row;
        //微缩号
        $row = '<row SourceFieldName="swh" NewFieldName="微缩号" value="' . $result['data']['swh'] . '"></row>';
        $xml = $xml . $row;
        //档案馆号
        $row = '<row SourceFieldName="dagdh" NewFieldName="档案管号" value="' . $result['data']['dagdh'] . '"></row>';
        $xml = $xml . $row;
        //数据类型
        $row = '<row SourceFieldName="sjlx" NewFieldName="数据类型" value="' . $result['data']['sjlx'] . '"></row>';
        $xml = $xml . $row;
        //附注
        $row = '<row SourceFieldName="fz" NewFieldName="附注" value="' . $result['data']['fz'] . '"></row>';
        $xml = $xml . $row;
        $xml = $xml . '</Root>';


        $result['data']['xml'] = $xml;


        if (!empty($jsonData)) {
            $jsonArr = json_decode($jsonData, true);
            foreach ($jsonArr as $key => $value) {
                $result['data']['ztsl'] = $value['page_number'];
            }
        }

        if (empty($result)) {
            return json(array('code' => 400, "data" => array(), 'message' => '请输入预览档案id'));
        } else {
            return json(array('code' => 200, "data" => $result['data'], 'message' => '请输入预览档案id'));
        }
    }

    function getTargetAreaPreview()
    {

        $data = request()->put();

        $id = $data['id'];
        $targetAreaType = $data['targetAreaType'];
        $targetAreaTypeRegular = $data['targetAreaTypeRegular'];


        if ($targetAreaType == 1) {
            $result = Db::table("zstp_article")->where(array("id" => $id))->find();

//            var_dump( $result);
            if (empty($result['content'])) {

                return json(array('code' => 400, "data" => array(), 'message' => '正文无内容'));
            }

            return json(array('code' => 200, "data" => $result['content'], 'message' => '获取成功'));

        }


        if ($targetAreaType == 3 && empty($targetAreaTypeRegular)) {
            return json(array('code' => 400, "data" => array(), 'message' => '请输入正则表达式'));
        }


        $result = MyHelper::getArticleInfoById($id);
        $content = $result['data']['content'];

        if ($targetAreaType == 1) {
            return array("code" => 200, "data" => $content, "message" => "");
        }


        if ($result['code'] == 400) {
            return $result;
        }

        $result = targetArea($content, $targetAreaTypeRegular);

        return json($result);


    }

//    function getTargetAreaMultiplePreview()
//    {
//        $data = request()->put();
//        $id = $data['id'];
//        $targetAreaType = $data['targetAreaType'];
//        $targetAreaTypeRegular = $data['targetAreaTypeRegular'];
//        if ($targetAreaType == 3 && empty($targetAreaTypeRegular)) {
//            return json(array('code' => 400, "data" => array(), 'message' => '请输入正则表达式'));
//        }
//
//
//        $result = MyHelper::getArticleInfoById($id);
//
//        if ($result['code'] == 400) {
//            return $result;
//        }
//
//        $content = $result['data']['content'];
//
//        if ($targetAreaType == 1) {
//            return array("code" => 200, "data" => $content, "message" => "");
//        }
//
//
//        $result = targetArea($id, $targetAreaType, $targetAreaTypeRegular);
//        return json($result);
//    }

    /** 每项内容标识
     * @return void
     */
    function getExpressionContent()
    {
        $data = request()->put();
        $id = $data['id'];
        $targetAreaType = $data['targetAreaType'];
        $targetAreaTypeRegular = $data['targetAreaTypeRegular'];
        if ($targetAreaType == 3 && empty($targetAreaTypeRegular)) {
            return json(array('code' => 400, "data" => array(), 'message' => '请输入正则表达式'));
        }

        $result = MyHelper::getArticleInfoById($id);
        $content = $result['data']['content'];


        if ($targetAreaType == 3) {
            $result = targetArea($content, $targetAreaTypeRegular);
            $content = $result['data'];
        }

        if (empty($data['regionalMultipleTypeRegular'])) {

            return json(array('code' => 400, "data" => array(), 'message' => '请输入正则表达式'));
        }


        $pattern = $data['regionalMultipleTypeRegular'];

        $result = multipleTargetArea($content, $pattern);

        if ($result ['code'] == 400) {

            return $result;
        }


        $list = $result['data'];

        $index = 0;
        $arr = [];
        foreach ($list as $key => $value) {
            $index = $index + 1;
            $str = "【抽取对象{$index}】" . $value;
            $arr[] = $str;
        }

        //数组转成字符串

        $txt = implode($arr, "</br>");


        return json(array('code' => 200, "data" => $txt, 'message' => '获取成功'));

    }

    /** 头实体预览
     * @return void
     */
    function getHeadPreview()
    {

        $data = request()->put();
        $type = $data['type'];

        if ($type == 1) {
            $entityText = "头实体";
        } else {
            $entityText = "尾实体";
        }


        $ArticleService = new  ArticleService();
        $result = $ArticleService->getArticleList($data);
        if ($result['code'] !== 200) {
            return $result;
        }
        $list = $result['data'];

        $headRegOrDic = $data['headRegOrDic'];

        $regOrDic = "";
        if ($headRegOrDic == 1) {
            $regOrDic = "正则";
        } else {
            $regOrDic = "字典";
        }


        $headReg = $data['headReg'];
        $headRadio = $data['headRadio'];
        $headDic = $data['headDic'];
        $headRegAndDic = $data['headRegAndDic'];
        $guding = $data['guding'];


        if ($headRadio == 1) {
            $radio = "单个目标";
        } else {
            $radio = "多个目标";
        }

        if (empty($data['headEntityTypeTxt'])) {
            return json(array('code' => 400, "data" => "", 'message' => "填写{$entityText}"));
        }

        $headEntityTypeTxt = $data['headEntityTypeTxt'];


        $result = MyHelper::getHeadEntity($headRegOrDic, $list, $headRadio, $headReg, $headDic, $headRegAndDic, $guding);


        if ($result['code'] == 200) {
            $forlist = $result['data'];
            $arr = array();
            foreach ($forlist as $key => $value) {
//                var_dump($value);
                $str = implode($value, "-|-");
                $str = "【抽取对象{$key}】-【{$entityText}】-【{$headEntityTypeTxt}】-【{$regOrDic}】:" . $str;
                $arr[] = $str;

            }


            $txt = "";
            if (!empty($arr)) {

                $txt = implode($arr, "</br></br>");
            }


            return json(array('code' => 200, "data" => $txt, 'message' => '获取成功'));
        } else {
            return json($result);

        }


    }


    function entityPreview()
    {


        $data = request()->put();
        $ArticleService = new  ArticleService();
        $result = $ArticleService->getArticleList($data);
        if ($result['code'] !== 200) {
            return $result;
        }
        $list = $result['data'];


        $entityRadio = $data['entityRadio'];

        $entityRegOrDic = $data['entityRegOrDic'];

        $headReg = $data['entityReg'];
        $headDic = $data['entityDic'];


        if ($entityRadio == 1) {
            $radio = "单个目标";
        } else {
            $radio = "多个目标";
        }

        $type = 1;
        if ($type == 1) {
            $entityText = "实体类型";
        } else {
            $entityText = "尾实体";
        }

        $headEntityTypeTxt = $data['entityType'];

        $regOrDic = "";
        if ($entityRegOrDic == 1) {
            $regOrDic = "正则";
        } else {
            $regOrDic = "字典";
        }

        if (empty($data['entityType'])) {
            return json(array('code' => 400, "data" => array(), 'message' => '填写实体类型'));
        }


        $result = MyHelper:: getHeadEntity($entityRegOrDic, $list, $entityRadio, $headReg, $headDic);


        if ($result['code'] == 200) {
            $forlist = $result['data'];
            $arr = array();
            foreach ($forlist as $key => $value) {
//                var_dump($value);
                $str = implode($value, "、");
                $str = "【抽取对象{$key}】-【{$regOrDic}】:" . $str;
                $arr[] = $str;

            }


            $txt = "";
            if (!empty($arr)) {

                $txt = implode($arr, "</br></br>");
            }


            return json(array('code' => 200, "data" => $txt, 'message' => '获取成功'));
        } else {
            return json($result);

        }

    }


    function extractcontentpreview()
    {

        $data = request()->put();
        $articleService = new  ArticleService();
        $result = $articleService->getArticleList($data);
        if ($result['code'] !== 200) {
            return json($result);
        }
        //目标中的内容
        $list = $result['data'];
        //抽取内容实体
        //实体参数验证
        $resultAlidate = $articleService->entityTypeAlidate($data);
        if ($resultAlidate['code'] !== 200) {
            return json($resultAlidate);
        }


        $regOrDic = $data['entityRegOrDic'];
        $radio = $data['entityRadio'];
        $reg = $data['entityReg'];
        $dic = $data['entityDic'];
        $entityType = $data['entityType'];
        //实体结果

        $resultEntity = MyHelper:: getHeadEntity($regOrDic, $list, $radio, $reg, $dic);


        if ($resultEntity['code'] != 200) {
            return json($resultEntity);
        }

        $entityList = $resultEntity ['data'];


//        die();


        // 属性结果list
        $extractContent = $data['extract_content'];


        $resultAttributelist = $articleService->inductiveAttributeListData($extractContent, $list);


        if ($resultAttributelist['code'] != 200) {
//            return json($resultAttributelist);
        }


        // 属性的list
        $attributelist = $resultAttributelist['data'];


        $attributeCount = count($attributelist);

        $relist = array();

        foreach ($entityList as $key => $value) {

            $count = count($value);
            //可能多个头实体值
            foreach ($value as $k => $v) {
                // 多个实体
                $txt = "头实体类型【{$entityType}】头实体值【{$v}】";
                //多个属性  --有属性
                if ($attributeCount > 0) {
                    for ($j = 0; $j < $attributeCount; $j++) {
                        $attributeName = $attributelist[$j]['attributeName'];
                        $attributeList = $attributelist[$j]['attributeList'][$key];
                        if (!empty($attributeList)) {
                            $attributeStr = implode($attributeList, "、");
                            $attrTxt = $txt . "属性名称【{$attributeName}】属性值【{$attributeStr}】";
                        } else {
                            $attrTxt = $txt . "属性名称【{$attributeName}】属性值 【无】";
                        }
                        $relist[] = $attrTxt;
                    }
                } else {
                    $relist[] = $txt;
                }


            }

        }


        $txt = implode($relist, "</br></br>");

        return json(array('code' => 200, "data" => $txt, 'message' => '获取成功'));

    }

    function getArticleist()
    {

        $data = request()->put();
        $length = $data['limit'];
        //$page = 2;
        if (empty($data['page'])) {
            $page = 0;
        } else {
            $page = $data['page'] - 1;
        }
        $offset = $page * $length;
        $map = array();

        if (!empty($data['id'])) {
            $map['number'] = array("=", $data['id']);
        }

        if (!empty($data['title'])) {
            $map['title'] = ['like', '%' . $data['title'] . '%'];
        }

        if (!empty($data['pub_time'][0]) && !empty($data['pub_time'][1])) {
            $map['pub_time'] = array(">", $data['pub_time'][0]);
            $map[' pub_time'] = array("<=", $data['pub_time'][1]);
        }
        if (!empty($data['template_id'])) {


            if ($data['template_id'] == -1) {
                $map['hit_template'] = array("=", 0);
            } else {
                $map['hit_template'] = array("=", $data['template_id']);
            }

        }


        if (!empty($data['batch_number'])) {
            $map['number'] = array("=", $data['batch_number']);
        }

        if (!empty($data['is_queue'])) {
            $map['is_queue'] = array("=", $data['is_queue']);
        }

        if (!empty($data['cid'])) {
            $map['zstp_article.id'] = array("=", $data['cid']);
        }

        $map['mode'] = array("=", "1");

        $result = Db::table('zstp_article')
            ->field(" *, zstp_article.id as id  ,zstp_article.status as status ")
            ->where($map)->field("*")
            ->join('zstp_template', 'zstp_article.hit_template = zstp_template.id', 'left')
            ->limit($offset, $length)
            ->order(array("zstp_article.id" => "asc"))
            ->select();


        foreach ($result as $key => $value) {
            $result[$key]["content"] = str_replace(array(" ", "&nbsp;", " "), '', $value['content']);
        }


        $totalCount = Db::table('zstp_article')->where($map)->where($map)->field("*")
            ->join('zstp_template', 'zstp_article.hit_template = zstp_template.id', 'left')
            ->count();


        return json(array(
            "code" => 200,
            "data" => array("resultList" => $result),
            "totalCount" => $totalCount,
        ));


    }


    public function validateTemplate()
    {
        $data = request()->put();


        if (empty($data['identifying_features'])) {
            return json(array('code' => 400, "data" => array(), 'message' => '请填写判定特征'));
        }

        $identifyingFeaturesData = $data['identifying_features'];


        foreach ($identifyingFeaturesData as $key => $value) {
            if (empty($value)) {
                return json(array("code" => 400, "data" => array(), "message" => "判定特征有数据未填写"));

            }
            $fordata = $value['value'];
            foreach ($fordata as $k => $v) {
                if (empty($v['titleOrContent'])) {
                    return json(array("code" => 400, "data" => array(), "message" => "标题或者内容未填写"));
                }
                if (empty($v['value'])) {
                    return json(array("code" => 400, "data" => array(), "message" => "正则未填写"));
                }
            }
        }


        $data['identifying_features'] = json_encode($data['identifying_features'], JSON_UNESCAPED_UNICODE);
        

        $templateArr[] = $data;

        $map['id'] = array("=", $data['article_id']);

        //查找文章
//        $article = Db::table("zstp_article")->where($map)->find();

        $articleArt = MyHelper::getArticleInfoById($data['article_id']);


        if ($articleArt['code'] != 200) {
            return json($articleArt);
        }


        $article = $articleArt['data'];


        if (empty($article)) {
            return json(array('code' => 400, "data" => array(), 'message' => '没有此id的文章'));
        }

        $Job = new \app\api\controller\Job();

 

        $resultTem = $Job->forTemplateArr($templateArr, $article);


        if ($resultTem['code'] == 400) {
            return json(array('code' => 400, "data" => array(), 'message' => '此文章不属于此模板'));
        }
        if ($resultTem['code'] == 200) {
            return json(array('code' => 200, "data" => array(), 'message' => '此文章属于此模板'));
        }


    }


    function getDocumentPage()
    {

        $data = request()->put();
        $length = $data['limit'];
        //$page = 2;
        if (empty($data['page'])) {
            $page = 0;
        } else {
            $page = $data['page'] - 1;
        }
        $offset = $page * $length;
        $map = array();

        if (!empty($data['dh'])) {
            $map['dh'] = array("=", $data['dh']);
        }

        if (!empty($data['content'])) {
            $map['content'] = ['like', '%' . $data['content'] . '%'];
        }

        if (!empty($data['bgqx'])) {
            $map['bgqx'] = array("=", $data['bgqx']);
        }


        if (!empty($data['jm'])) {
            $map['jm'] = array("=", $data['jm']);
        }

        if (!empty($data['lbh'])) {
            $map['lbh'] = array("=", $data['lbh']);
        }

        if (!empty($data['qzh'])) {
            $map['qzh'] = array("=", $data['qzh']);
        }

        if (!empty($data['sj'])) {
            $map['sj'] = array("=", $data['sj']);
        }

        if (!empty($data['tm'])) {
            $map['tm'] = array("=", $data['tm']);
        }

        if (!empty($data['wjbh'])) {
            $map['wjbh'] = array("=", $data['wjbh']);
        }

        if (!empty($data['wz'])) {
            $map['wz'] = array("=", $data['wz']);
        }

        if (!empty($data['ztc'])) {
            $map['ztc'] = array("=", $data['ztc']);
        }


        if ($data['audit_status'] == 1) {
            $map['audit_status'] = array("=", $data['audit_status']);
        }

        if ($data['audit_status'] == "0") {
            $map['audit_status'] = array("=", $data['audit_status']);
        }

        //合成pdf 的文件
        $map['is_synpdf'] = array("=", 1);


        $result = Db::table('zstp_article')
            ->field("*")
            ->where($map)
            ->limit($offset, $length)
            ->order(array("zstp_article.id" => "desc"))
            ->select();

//        var_dump(Db::getLastsql());

        $totalCount = Db::table('zstp_article')->where($map)->where($map)
            ->count();


        return json(array(
            "code" => 200,
            "data" => array("resultList" => $result),
            "totalCount" => $totalCount,
        ));


    }

    function getDocumentPageSer()
    {

        $data = request()->put();
        $length = $data['limit'];
        //$page = 2;
        if (empty($data['page'])) {
            $page = 0;
        } else {
            $page = $data['page'] - 1;
        }
        $offset = $page * $length;
        $map = array();

        if (!empty($data['dh'])) {
            $map['dh'] = array("=", $data['dh']);
        }

        if (!empty($data['content'])) {
            $map['content'] = ['like', '%' . $data['content'] . '%'];
        }

        if (!empty($data['bgqx'])) {
            $map['bgqx'] = array("=", $data['bgqx']);
        }


        if (!empty($data['jm'])) {
            $map['jm'] = array("=", $data['jm']);
        }

        if (!empty($data['lbh'])) {
            $map['lbh'] = array("=", $data['lbh']);
        }

        if (!empty($data['qzh'])) {
            $map['qzh'] = array("=", $data['qzh']);
        }

        if (!empty($data['sj'])) {
            $map['sj'] = array("=", $data['sj']);
        }

        if (!empty($data['tm'])) {
            $map['tm'] = array("=", $data['tm']);
        }

        if (!empty($data['wjbh'])) {
            $map['wjbh'] = array("=", $data['wjbh']);
        }

        if (!empty($data['wz'])) {
            $map['wz'] = array("=", $data['wz']);
        }

        if (!empty($data['ztc'])) {
            $map['ztc'] = array("=", $data['ztc']);
        }


        // if ($data['audit_status'] == 1) {
        //     $map['audit_status'] = array("=", $data['audit_status']);
        // }

        // if ($data['audit_status'] == "0") {
        //     $map['audit_status'] = array("=", $data['audit_status']);
        // }

        //合成pdf 的文件
        // $map['audit_status'] = array("=", 1);


        $result = Db::table('zstp_article')
            ->field("*")
            ->where($map)
            ->limit($offset, $length)
            ->order(array("zstp_article.id" => "desc"))
            ->select();

//        var_dump(Db::getLastsql());

        $totalCount = Db::table('zstp_article')->where($map)->where($map)
            ->count();


        return json(array(
            "code" => 200,
            "data" => array("resultList" => $result),
            "totalCount" => $totalCount,
        ));


    }

    function getfulltxtById()
    {
        $data = request()->put();
        $id = $data['_id'];
        // $searchContent = $data['searchContent'];
        $es = config("es");
        $client = ClientBuilder::create()->setHosts([$es . ':9200'])->build();
// 构建查询请求
        $params = [
            'index' => 'my_index', // 你的索引名
            'body' => [
                'query' => [
                    'bool' => [
                        'must' => [
                            ['term' => ['_id' => $id]], // 精确匹配文档ID
                            // ['match' => ['content' => $searchContent]] // 匹配查询内容
                        ]
                    ]
                ],
                '_source' => ['id', 'content', "dh"], // 确保返回 id 和 content 字段的内容
                'highlight' => [
                    'pre_tags' => ["<em style='color: red'>"], // 高亮前缀标签
                    'post_tags' => ['</em>'], // 高亮后缀标签
                    'fields' => [
                        'content' => [ // 返回一个高亮片段
                            'fragment_size' => 0, // 不进行片段化，返回整个字段
                            'number_of_fragments' => 0, // 返回整个字段
                            'no_match_size' => 150000, // 如果没有匹配项，则返回的文本长度
                            'force_source' => true // 强制从源文档中提取高亮内容
                        ]
                    ]
                ]
            ]
        ];

        $response = $client->search($params);

        return json(array(
            "code" => 200,
            "data" => $response['hits']['hits'][0],
        ));


    }

    function deleteEsById()
    {

        $es = config("es");
        $client = ClientBuilder::create()->setHosts([$es . ':9200'])->build();
        // 创建Elasticsearch客户端


// 定义索引名称
        $indexName = 'my_index'; // 你的索引名称

// 构建删除参数
        $params = [
            'index' => $indexName,
            'body' => [
                'query' => [
                    'match' => [
                        'id' => 1 // 根据 "id" 字段等于 1 的条件删除文档
                    ]
                ]
            ]
        ];

        try {
            // 执行删除操作
            $response = $client->deleteByQuery($params);

            // 输出删除结果
            print_r($response);
        } catch (Exception $e) {
            // 处理异常
            echo "Error: " . $e->getMessage();
        }
    }

    function getDocumentQwjsPage()
    {
        $data = request()->put();
        $length = $data['limit'];
        if (empty($data['page'])) {
            $page = 0;
        } else {
            $page = $data['page'] - 1;
        }
        $offset = $page * $length;
        $map = array();

        $es = config("es");

        $client = ClientBuilder::create()->setHosts([$es . ':9200'])->build();
            
    

        $searchContent = $data['content'];

        // 获取前端传来的每页数量和当前页码
        $pageSize = $length;
        $currentPage = $page;

        // 计算从哪里开始获取数据
        $from = $currentPage * $pageSize;

        // 构建滚动查询请求
        $params = [
            'index' => 'my_index', // 你的索引名
            'body' => [
                'size' => $pageSize,
                'query' => [
                    'match' => [ // 使用 match 查询来处理中文文本检索
                        'content' => $searchContent
                    ]
                ],
                'highlight' => [
                    'pre_tags' => ["<em style='color: red'>"], // 高亮前缀标签
                    'post_tags' => ['</em>'], // 高亮后缀标签
                    "fields" => [
                        'content' => new \stdClass()
                    ]
                ]
            ],
            'scroll' => '1m' // 设置滚动时间窗口
        ];

        // 执行第一次搜索请求，获取滚动游标
        $response = $client->search($params);




//        var_dump($response);

        $scrollId = $response['_scroll_id'];
        $hits = $response['hits']['hits'];
        // 获取总记录数
        $totalCount = $response['hits']['total']['value'];

        // 处理返回的数据
        $data = [];
        foreach ($hits as $hit) {
            $data[] = $hit;
        }

        // 如果需要更多数据，继续滚动
        while (count($hits) > 0 && count($data) < $from + $pageSize) {
            $scrollParams = [
                'scroll' => '1m',
                'scroll_id' => $scrollId
            ];
            $scrollResponse = $client->scroll($scrollParams); // 使用 scroll API
            $hits = $scrollResponse['hits']['hits'];
            foreach ($hits as $hit) {
                $data[] = $hit;
            }
        }

        // 清除滚动游标
        $client->clearScroll(['scroll_id' => [$scrollId]]);
        $data = array_slice($data, $offset, $length);


        return json(array(
            "code" => 200,
            "data" => array("resultList" => $data),
            "totalCount" => $totalCount,
        ));
    }

    function getDocumentById()
    {
        $data = request()->put();


        $serverIp = config("kgFilePath");

        $id = $data['id'];

        $result = Db::table('zstp_article')->where(array("id" => $data['id']))->find();


        $str = md5($id);

        $url = $serverIp . "/pdf/data/{$result['id']}/" . "{$str}_monolayer.pdf";;

        $result['pdf_url'] = $url;

        $newResult = array();
        $newResult['id'] = $result ['id'];
        $newResult['pdf_url'] = $url;
        $newResult['content'] = $result['content'];
        return json(array(
            "code" => 200,
            "data" => $newResult

        ));
    }


    function indexRulesHitLogInsertt($data, $key)
    {

        $dataInsert = array();
        $dataInsert['index_object'] = $key;
        $dataInsert['review_time'] = date("Y-m-d H:i:s");
        $dataInsert['article_id'] = $data['id'];

        if (empty($data[$key]['guizeId'])) {
            $dataInsert['by_hand_input'] = $data[$key]['value'];
        } else {
            $dataInsert['index_id'] = $data[$key]['guizeId'];
            $dataInsert['recommended'] = $data[$key]['value'];
        }

        Db::table("zstp_index_rules_hit_log")->insert($dataInsert);

    }

    function uptDocument()
    {


        $data = request()->put();

        $updateData = array();
        //档号
        if (!$data['dh']['value'] == "") {
            $updateData['dh'] = $data['dh']['value'];
            $mapInc['id'] = $data['dh']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');
            $this->indexRulesHitLogInsertt($data, "dh");
        }
        //主题词
        if (!$data['ztc']['value'] == "") {
            $updateData['ztc'] = $data['ztc']['value'];
            $mapInc['id'] = $data['ztc']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');
            $this->indexRulesHitLogInsertt($data, "ztc");
        }
        //密级
        if (!$data['mj']['value'] == "") {
            $updateData['mj'] = $data['mj']['value'];
            $mapInc['id'] = $data['mj']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');
            $this->indexRulesHitLogInsertt($data, "mj");
        }
        //保管期限
        if (!$data['bgqx']['value'] == "") {
            $updateData['bgqx'] = $data['bgqx']['value'];
            $mapInc['id'] = $data['bgqx']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');
            $this->indexRulesHitLogInsertt($data, "bgqx");
        }

        //全宗号
        if (!$data['qzh']['value'] == "") {
            $updateData['qzh'] = $data['qzh']['value'];
            $mapInc['id'] = $data['qzh']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');
            $this->indexRulesHitLogInsertt($data, "qzh");
        }

        //分类号
        if (!$data['flh']['value'] == "") {
            $updateData['flh'] = $data['flh']['value'];
            $mapInc['id'] = $data['flh']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');

            $this->indexRulesHitLogInsertt($data, "flh");
        }

        //全文标识

//        if (!$data['qwbs']['value'] == "") {
//            $updateData['qwbs'] = $data['flh']['value'];
//            $mapInc['id'] = $data['qwbs']['guizeId'];
//            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');
//
//            $this->indexRulesHitLogInsertt($data, "qwbs");
//        }

        //类别号
        if (!$data['lbh']['value'] == "") {
            $updateData['lbh'] = $data['lbh']['value'];
            $mapInc['id'] = $data['lbh']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');

            $this->indexRulesHitLogInsertt($data, "lbh");
        }
        //文种
        if (!$data['wz']['value'] == "") {
            $updateData['wz'] = $data['wz']['value'];
            $mapInc['id'] = $data['wz']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');

            $this->indexRulesHitLogInsertt($data, "wz");
        }

        //时间
        if (!$data['sj']['value'] == "") {

            $updateData['sj'] = $data['sj']['value'];
            $mapInc['id'] = $data['sj']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');
            $this->indexRulesHitLogInsertt($data, "sj");
        }
        //题名
        if (!$data['tm']['value'] == "") {
            $updateData['tm'] = $data['tm']['value'];
            $mapInc['id'] = $data['tm']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');

            $this->indexRulesHitLogInsertt($data, "tm");
        }
        //文件编号
        if (!$data['wjbh']['value'] == "") {
            $updateData['wjbh'] = $data['wjbh']['value'];
            $mapInc['id'] = $data['wjbh']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');
            $this->indexRulesHitLogInsertt($data, "wjbh");
        }

        //载体类型
        if (!$data['ztlx']['value'] == "") {
            $updateData['ztlx'] = $data['ztlx']['value'];
        }
        //载体规格
        if (!$data['ztgg']['value'] == "") {
            $updateData['ztgg'] = $data['ztgg']['value'];
        }
        //责任者
        if (!$data['zrz']['value'] == "") {
            $updateData['zrz'] = $data['zrz']['value'];
            $mapInc['id'] = $data['zrz']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');
            $this->indexRulesHitLogInsertt($data, "zrz");
        }
        //缩微号
        if (!$data['swh']['value'] == "") {
            $updateData['swh'] = $data['swh']['value'];
            $mapInc['id'] = $data['swh']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');
            $this->indexRulesHitLogInsertt($data, "swh");
        }
        //档案馆号
        if (!$data['dagdh']['value'] == "") {
            $updateData['dagdh'] = $data['dagdh']['value'];
            $mapInc['id'] = $data['dagdh']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');
            $this->indexRulesHitLogInsertt($data, "dagdh");
        }
        // 数据类型
        if (!$data['sjlx']['value'] == "") {
            $updateData['sjlx'] = $data['sjlx']['value'];

        }


        //文本

        $updateData['content'] = $data['content'];


        //附注
        if (!$data['fz'] == "") {
            $updateData['fz'] = $data['fz']['value'];
            $mapInc['id'] = $data['fz']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');
            $this->indexRulesHitLogInsertt($data, "fz");
        }

        //案卷号
        if (!$data['ajh']['value'] == "") {
            $updateData['ajh'] = $data['ajh']['value'];
            $mapInc['id'] = $data['ajh']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');
            $this->indexRulesHitLogInsertt($data, "ajh");
        }

        //件号
        if (!$data['jh']['value'] == "") {
            $updateData['jh'] = $data['jh']['value'];
            $mapInc['id'] = $data['jh']['guizeId'];
            Db::table("zstp_index_sys")->where($mapInc)->setInc('hits');
            $this->indexRulesHitLogInsertt($data, "jh");
        }


        $updateData['audit_status'] = 1;


        $result = Db::table('zstp_article')->where(array("id" => $data['id']))->update($updateData);


        $rid = "";
        $mapSuditStatus['audit_status'] = array("=", 0);
        $artId = Db::table('zstp_article')->field("id")->where($mapSuditStatus)->find();


        if (!empty($artId)) {
            $rid = $artId['id'];
        } else {
            return json(array("code" => 400, "data" => null, "message" => "没有可标引的文章了"));
        }


        return json(array("code" => 200, "data" => $rid, "message" => "修改成功"));


    }


    function getTextByField()
    {

        $data = request()->put();
        $key1 = $data['name'];
        $map["status"] = array("=", 1);
        $map["is_delete"] = array("=", 0);
        $map["index_object"] = array("=", $data['name']);
//        $map["id"] = array("=", 28);

        //查所有标题规则
        $indexSysList = Db::table('zstp_index_sys')->where($map)->order(array("hits" => "desc"))->select();

        $articleResult = array();
        $articleResult['id'] = $data['id'];
        $indexSystem = new  Indexsystem();
        $data = array();

        $datatiHuan = Db::table("zstp_conf")->field("value")->where(array("type" => 2))->select();
        foreach ($indexSysList as $value) {
            $result = $indexSystem->work($value, $articleResult);


            if ($result['code'] == 200 && $result['data'] != "") {


                if (!empty($datatiHuan)) {
                    $serArrayTi = array();
                    $repArrayTi = array();
                    foreach ($datatiHuan as $key => $v) {
                        $ex = explode(",", $v['value']);
                        $serArrayTi[] = $ex[0];
                        $repArrayTi[] = $ex[1];
                    }
                    $result['data'] = str_replace($serArrayTi, $repArrayTi, $result['data']);
                }

                $text = "{$value['id']}号标引规则值：“{$result['data']}”";
                $guizheId = $value['id'];
                $value = $result['data'];
                $arr = [];
                $arr['text'] = $text;
                $arr['guizheId'] = $guizheId;

                $arr['value'] = $value;

                $arr['key'] = $key1;
                $data [] = $arr;
            }
        }


        if (count($data) == 1) {
            return json(array("code" => 200, "data" => $data));
        }

        if (count($data) == 0) {
            return json(array("code" => 200, "data" => $data));
        }

        $arr = $data;
        $identicalStatus = false;

// 统计每个 value 的出现次数
        $valueCounts = [];
        foreach ($arr as $item) {
            $value = $item['value'];
            if (!isset($valueCounts[$value])) {
                $valueCounts[$value] = 0;
            }
            $valueCounts[$value]++;
            if ($identicalStatus == false) {
                if ($valueCounts[$value] > 0) {
                    $identicalStatus = true;
                }
            }
        }

        if ($identicalStatus == true) {
            // 根据 value 的出现次数排序数组
            usort($arr, function ($a, $b) use ($valueCounts) {
                $countA = isset($valueCounts[$a['value']]) ? $valueCounts[$a['value']] : 0;
                $countB = isset($valueCounts[$b['value']]) ? $valueCounts[$b['value']] : 0;
                return $countB <=> $countA;
            });

            $data = $arr;

        }


        return json(array("code" => 200, "data" => $data));

    }

    function saveOrUpIndexsysFind()
    {
        $data = request()->put();

        $id = $data['id'];

        if (empty($id)) {
            return json(array('code' => 400, "data" => array(), 'message' => '请选择文章'));
        }

        $result = MyHelper::getArticleInfoById($id);
        $content = $result['data']['content'];

//        var_dump($result);

        $type = $data['headRegOrDic'];


        if ($type == 4) {

            $newResult = $result['data'];
            $dbfimport = new  Dbfimport();
            $jsonData = $dbfimport->getUniqueString($id, 3);
            //读取json 文件
            $jsonData = file_get_contents($jsonData, true);
            $jsonArr = json_decode($jsonData, true);


            if (empty($jsonArr[0]['json_results'])) {
                return json(array("code" => 400, "公章没有内容"));
            }

            $arr = [];
            foreach ($jsonArr as $key => $value) {

                foreach ($value['json_results'] as $k => $v) {
                    $arr[] = $v;
                }

            }


            $mdzfc = $data['mdzfc'];

            if (empty($mdzfc)) {
                return json(array("code" => 400, "message" => "请输入瞄点字符串"));
            }


            $xStartDs = $data['xStart'];

            if ($xStartDs == "") {
                return json(array("code" => 400, "message" => "请输入x坐标开始"));
            }

            $xEndDs = $data['xEnd'];

            if ($xEndDs == "") {
                return json(array("code" => 400, "message" => "请输入x坐标结束"));
            }

            $xStartName = $data['xStartName'];

            if ($xStartName == "") {
                return json(array("code" => 400, "message" => "请输入x坐标开始名称"));
            }

            $xEndName = $data['xEndName'];

            if ($xEndName == "") {
                return json(array("code" => 400, "message" => "请输入x坐标结束名称"));
            }

            $yStartName = $data['yStartName'];


            if ($yStartName == "") {
                return json(array("code" => 400, "message" => "请输入y坐标开始名称"));
            }


            $yEndName = $data['yEndName'];

            if ($yEndName == "") {
                return json(array("code" => 400, "message" => "请输入y坐标结束名称"));
            }

            $yStartDs = $data['yStart'];

            if ($yStartDs == "") {
                return json(array("code" => 400, "message" => "请输入y坐标开始"));
            }

            $yEndDs = $data['yEnd'];
            if ($yEndDs == "") {
                return json(array("code" => 400, "message" => "请输入y坐标结束"));
            }

            $result = MyHelper::dingWei($arr, $mdzfc, $xStartName, $xEndName, $yStartName, $yEndName, $xStartDs, $xEndDs, $yStartDs, $yEndDs);

            if (!empty($data['osName']) && !empty($data['newName'])) {

                //替换字符串
                $str = str_replace($data['osName'], $data['newName'], $result['data']);

                $result['data'] = $str;

            }


            if ($result['code'] == 400) {
                return json($result);
            } else {
                $result = $this->saveOrUpIndexsysDo($data);
                return json($result);

            }

        }


        if (empty($data['targetAreaType'])) {
            return json(array("code" => 400, "message" => "请选择目标区域"));
        }


        $targetAreaType = $data['targetAreaType'];

        if ($targetAreaType == 3) {
            // 正则 文章 内容

            if (empty($data['targetAreaTypeRegular'])) {
                return json(array("code" => 400, "message" => "目标区域请输入正则表达式"));
            }

            $targetAreaTypeRegular = $data['targetAreaTypeRegular'];

            $result = targetArea($content, $targetAreaTypeRegular);

            if ($result['code'] == 200) {
                $content = $result['data'];
            } else {


                return json($result);
            }

        }


        if (empty($content)) {
            return json(array('code' => 400, "data" => array(), 'message' => '正文无内容'));
        }


        $Reg = $data['headReg'];

        $Dic = $data['headDic'];

        $headRegAndDic = "";
        if (!empty($data['headRegAndDic'])) {
            $headRegAndDic = $data['headRegAndDic'];
        }


        $result = MyHelper::biaoyin($content, $type, $Reg, $Dic, $headRegAndDic);


        if ($result['code'] == 400) {
            return json($result);
        } else {
            $result = $this->saveOrUpIndexsysDo($data);
            return json($result);
        }


    }

    function deldelArticleById()
    {

        $data = request()->put();

        $map = array();

        $map['id'] = array("=", $data['id']);

        $resutl = Db::table("zstp_article")->where("id", $data['id'])->delete();

        if ($resutl) {
            $dbfimport = new  Dbfimport();
            $jsonData = $dbfimport->deleteFile($data['id']);
            return json(array("code" => 200, "data" => array(), 'message' => '删除成功'));
        } else {
            return json(array("code" => 400, "data" => array(), 'message' => '删除失败'));
        }


    }


    function getArticleDetailsById()
    {

        $data = request()->put();


        $data = request()->put();

        if (empty($data['id'])) {
            return json(array('code' => 400, 'message' => '请输入预览档案id'));
        }

        $id = $data['id'];

        $result = MyHelper::getArticleInfoByIdAbutBiaoyin($data['id']);

        $resultzrdhh = MyHelper::getArticleInfoById($data['id']);

        $result['data']['contentzrdhh'] = $resultzrdhh['data']['content'];


        $serverIp = config("kgFilePath");


        $id = $data['id'];
        $str = md5($id);
        $url = $serverIp . "/pdf/data/{$id}/" . "{$str}_monolayer.pdf";;

        $result['data']['pdf_url'] = $url;
        $Douburl = $serverIp . "/pdf/data/{$id}/" . "{$str}_doublelayer.pdf";;
        $result['data']['doupdf_url'] = $Douburl;


        //计算载体数量

        $Dbfimport = new Dbfimport();
        $jsonPath = $Dbfimport->getUniqueString($id, 3);
//        $jsonData = file_get_contents($jsonPath);

        $result['data']['ztsl'] = null;

        $list = array();


        //唯一标识


        //档号
        $list[] = array("key" => "档号", "value" => $result['data']['dh']);

        //主题词


        $list[] = array("key" => "主题词", "value" => $result['data']['ztc']);

        //密级


        $list[] = array("key" => "密级", "value" => $result['data']['mj']);

        //保管期限


        $list[] = array("key" => "保管期限", "value" => $result['data']['bgqx']);

        //全宗号


        //分类号

        $list[] = array("key" => "分类号", "value" => $result['data']['flh']);

        //案卷号


        $list[] = array("key" => "案卷号", "value" => $result['data']['ajh']);

        //件号


        $list[] = array("key" => "件号", "value" => $result['data']['jh']);

        //关键词


        $list[] = array("key" => "关键词", "value" => $result['data']['gjc']);

        //类别号


        $list[] = array("key" => "类别号", "value" => $result['data']['lbh']);

        //文种

        $list[] = array("key" => "文种", "value" => $result['data']['wz']);

        //时间


        $list[] = array("key" => "时间", "value" => $result['data']['sj']);

        //题名


        $list[] = array("key" => "题名", "value" => $result['data']['tm']);

        //文件编号


        $list[] = array("key" => "文件编号", "value" => $result['data']['wjbh']);

        //载体类型


        $list[] = array("key" => "载体类型", "value" => $result['data']['ztlx']);

        //载体数量

        $list[] = array("key" => "载体数量", "value" => $result['data']['ztsl']);

        //载体单位


        $list[] = array("key" => "载体单位", "value" => $result['data']['ztdw']);

        //载体规格


        $list[] = array("key" => "载体规格", "value" => $result['data']['ztgg']);

        //责任者


        $list[] = array("key" => "责任者", "value" => $result['data']['zrz']);

        //微缩号

        $list[] = array("key" => "微缩号", "value" => $result['data']['swh']);

        //档案馆号


        $list[] = array("key" => "档案管号", "value" => $result['data']['dagdh']);

        //数据类型


        $list[] = array("key" => "数据类型", "value" => $result['data']['sjlx']);

        //附注


        $list[] = array("key" => "附注", "value" => $result['data']['fz']);
        $list[] = array("key" => "文本", "value" => $resultzrdhh['data']['content']);


        $result['data']['list'] = $list;

        $gzsblist = [];

        $gzsblist[] = array("key" => "公章名称", "value" => $result['data']['gzmc']);
        $gzsblist[] = array("key" => "公章编号", "value" => $result['data']['gzbh']);
        $gzsblist[] = array("key" => "公章用途", "value" => $result['data']['gzyt']);


        $result['data']['gzsblist'] = $gzsblist;

        if (!empty($jsonData)) {
            $jsonArr = json_decode($jsonData, true);
            foreach ($jsonArr as $key => $value) {
                $result['data']['ztsl'] = $value['page_number'];
            }
        }

        if (empty($result)) {
            return json(array('code' => 400, "data" => array(), 'message' => '请输入预览档案id'));
        } else {
            return json(array('code' => 200, "data" => $result['data'], 'message' => '请输入预览档案id'));
        }

    }


    function manipulation()
    {


        $data = request()->put();


        $resultProject = Db::table("zstp_project")->where(array("id" => $data ['project_id']))->find();
        $graphDatabase = $resultProject ['graph_database'];


        if ($data['type'] == 1) {
            $cypher = "MATCH (n) WHERE n.name IS NOT NULL AND n.name =~ '^(?=.*[A-Za-z])[A-Za-z0-9\\s\\-]+$' DETACH DELETE n RETURN count(DISTINCT n) AS deletedNodes;";
        } else {

            $db = config("neo4j.database");

            $cypher = 'MATCH (other:`' . $db . '.Others`)
OPTIONAL MATCH (person:`' . $db . '.Person` {name: other.name})
WITH other, person
WHERE person IS NOT NULL
CALL apoc.refactor.mergeNodes([person, other], {properties: "combine", mergeRels: true}) YIELD node
RETURN node;';
        }


        $result = neo4j_connect_entity($cypher, $graphDatabase);
//        var_dump($result);die();
//        $result = '{"results":[{"columns":["deletedNodes"],"data":[{"row":[2],"meta":[null]}]}],"errors":[],"commit":"http://192.168.2.108:7474/db/test/tx/13/commit","transaction":{"expires":"Mon, 6 Jan 2025 08:32:50 GMT"}}';

        $reData = json_decode($result, true);
//
//        var_dump($reData);


        if ($data['type'] == 1) {

//        var_dump($reData['results'][0]['data'][0]['row'][0]);

            if ($reData['results'][0]['data'][0]['row'][0]) {

                return json(array('code' => 200, "data" => array(), 'message' => '治理成功，删除了' . $reData['results'][0]['data'][0]['row'][0] . '个实体及其相关关系。'));
            } else {
                return json(array('code' => 400, "data" => array(), 'message' => '治理失败'));
            }
        }

        if ($data['type'] == 2) {


            return json(array('code' => 200, "data" => array(), 'message' => '处理成功'));


        }

    }


    function autobiaoyin()
    {

        $data = request()->put();

        $id = $data['id'];

        $OllamaService = new OllamaService();

        $result = $OllamaService->automaticindexing($id);

        var_dump($result['message']['content']);

    }


    function xiaozhun()
    {

//        echo  '{
//    "code": 200,
//    "data": {
//        "correction_results": "2024\/8\/5 13:47 干部任前公示公告（2023年12月29日）_安徽省人民政府\n索引号：00298627-2\/202312-00050 信息分类：人事任免\n发布机构：安徽省人民政府办公厅 生成日期：2023\/12\/29\n名称：干部任前公示公告（2023年12月29日）\n文号：\n关键词：\n干部任前公示公告（2023年12月29日）\n为在干部选拔任用工作中进一步扩大民主，广泛听取群众意见，把干部选好、选准，根据《党政领导干部选拔任用工作条例》规定，现对以下拟任人选进行公示：\n朱浩东，男，汉族，1971年11月生，在职研究生学历，工商管理硕士，中共党员，现任池州市委副书记、市长，拟任省辖市市委书记；\n王海霞，女，汉族，1969年12月生，省委党校研究生学历，中共党员，现任合肥市蜀山区委书记，拟提名为省辖市人大常委会副主任候选人：\n罗平，男，汉族，1967年9月生，大学学历，文学学士，中共党员，现任合肥市政府秘书长、党组成员、机关党组书记，拟提名为省辖市政协副主席候选人：\n陈明，男，汉族，1966年2月生，中央党校大学学历，中共党员，现任合肥市市场监督管理局党组书记、二级巡视员，拟提名为省辖市政协副主席候选人：\n徐涛，男，汉族，1968年7月生，大学学历，经济学学士，中共党员，现任淮北市政府秘书长、党组成员、机关党组书记，拟提名为省辖市人大常委会副主任候选人：\n岳军芝，女，汉族，1970年2月生，大学学历，中共党员，现任淮北市人力资源和社会保障局局长、党组书记，市委组织部副部长（兼），拟提名为省辖市政协副主席候选人：\n陈忠新，男，汉族，1965年4月生，大学学历，医学学士，九三学社社员，现任九三学社淮北市委会主委，拟提名为省辖市政协副主席候选人：\n葛生，男，汉族，1966年10月生，中央党校研究生学历，法学学士，中共党员，现任亳州市委党校常务副校长，拟提名为省辖市政协副主席候选人：\n张传宾，男，汉族，1968年6月生，中央党校大学学历，中共党员，现任亳州市政府秘书长、党组成员、机关党组书记，拟提名为省辖市政协副主席候选人：\n李丰，男，汉族，1973年12月生，省委党校研究生学历，民进会员，现任亳州市住房和城乡建设局局长、民进亳州市委会主委，拟提名为省辖市政协副主席候选人：\n王鹏，男，汉族，1968年5月生，中央党校大学学历，中共党员，现任宿州市审计局局长、党组书记，拟提名为省辖市政协副主席候选人：\n乔树伟，男，汉族，1966年12月生，大学学历，文学学士，中共党员，现任蚌埠市委副秘书长、市委办公室主任，拟提名为省辖市政协副主席候选人：\n苟异然，男，汉族，1971年9月生，省委党校研究生学历，中共党员，现任蚌埠市水利局局长、党委书记，拟提名为省辖市政协副主席候选人：",
//        "summary": "对原文进行了校正，纠正了“安微”、“千部”的错别字，并调整了换行和标点符号使其更加规范。"
//    },
//    "message": "处理成功"
//}';
//die();

        $data = request()->put();

        $id = $data['id'];

        $OllamaService = new OllamaService();

        $result = $OllamaService->autoxiaozhun($id);


        preg_match('/```json\s*({.*?})\s*```/s', $result['message']['content'], $matches);


        $datArr = json_decode($matches[1], true);


        echo '{
    "code": 200,
    "data": {
        "correction_results": "2024\/8\/5 13:47 干部任前公示公告（2023年12月29日）_安徽省人民政府\n索引号：00298627-2\/202312-00050 信息分类：人事任免\n发布机构：安徽省人民政府办公厅 生成日期：2023\/12\/29\n名称：干部任前公示公告（2023年12月29日）\n文号：\n关键词：\n干部任前公示公告（2023年12月29日）\n为在干部选拔任用工作中进一步扩大民主，广泛听取群众意见，把干部选好、选准，根据《党政领导干部选拔任用工作条例》规定，现对以下拟任人选进行公示：\n朱浩东，男，汉族，1971年11月生，在职研究生学历，工商管理硕士，中共党员，现任池州市委副书记、市长，拟任省辖市市委书记；\n王海霞，女，汉族，1969年12月生，省委党校研究生学历，中共党员，现任合肥市蜀山区委书记，拟提名为省辖市人大常委会副主任候选人：\n罗平，男，汉族，1967年9月生，大学学历，文学学士，中共党员，现任合肥市政府秘书长、党组成员、机关党组书记，拟提名为省辖市政协副主席候选人：\n陈明，男，汉族，1966年2月生，中央党校大学学历，中共党员，现任合肥市市场监督管理局党组书记、二级巡视员，拟提名为省辖市政协副主席候选人：\n徐涛，男，汉族，1968年7月生，大学学历，经济学学士，中共党员，现任淮北市政府秘书长、党组成员、机关党组书记，拟提名为省辖市人大常委会副主任候选人：\n岳军芝，女，汉族，1970年2月生，大学学历，中共党员，现任淮北市人力资源和社会保障局局长、党组书记，市委组织部副部长（兼），拟提名为省辖市政协副主席候选人：\n陈忠新，男，汉族，1965年4月生，大学学历，医学学士，九三学社社员，现任九三学社淮北市委会主委，拟提名为省辖市政协副主席候选人：\n葛生，男，汉族，1966年10月生，中央党校研究生学历，法学学士，中共党员，现任亳州市委党校常务副校长，拟提名为省辖市政协副主席候选人：\n张传宾，男，汉族，1968年6月生，中央党校大学学历，中共党员，现任亳州市政府秘书长、党组成员、机关党组书记，拟提名为省辖市政协副主席候选人：\n李丰，男，汉族，1973年12月生，省委党校研究生学历，民进会员，现任亳州市住房和城乡建设局局长、民进亳州市委会主委，拟提名为省辖市政协副主席候选人：\n王鹏，男，汉族，1968年5月生，中央党校大学学历，中共党员，现任宿州市审计局局长、党组书记，拟提名为省辖市政协副主席候选人：\n乔树伟，男，汉族，1966年12月生，大学学历，文学学士，中共党员，现任蚌埠市委副秘书长、市委办公室主任，拟提名为省辖市政协副主席候选人：\n苟异然，男，汉族，1971年9月生，省委党校研究生学历，中共党员，现任蚌埠市水利局局长、党委书记，拟提名为省辖市政协副主席候选人：",
        "summary": "对原文进行了校正，纠正了“安微”、“千部”的错别字，并调整了换行和标点符号使其更加规范。"
    },
    "message": "处理成功"
}';


        // return json(array('code' => 200, "data" => $datArr, 'message' => '处理成功'));


    }

    function jiaozhunbuttomBaocun()
    {

        $data = request()->put();
        $result = Db::table("zstp_article")->where(array("id" => $data['id']))->update(array("content" => $data['content']));
        return json(array('code' => 200, "data" => $result, 'message' => '处理成功'));
    }

    //
    function getArticleByidabutBiaoyinAuto()
    {


        //查开关走哪里

        $dataVl = Db::table("zstp_vl_conf")->where(array("type" => "vl"))->field("value")->find();

        $statusVl = $dataVl['value'];

        $data = request()->put();
        if (empty($data['id'])) {
            //没有id找出id 这是模拟数据
           
            $mapb['z_status'] = array("=", 0);
            $data = Db::table('zstp_processdocument_article')->order('id asc')->where($mapb)->find();
            if (empty($data)) {
                return json(array('code' => 200, "data" => array(), 'message' => ''));
            }
        }


        $id = $data['id'];
        $data['ztlx'] = "纸张";
        $data['ztdw'] = "张";
        $data['ztgg'] = "A4";

    
        //唯一标识
        $xml = '<?xml version="1.0" encoding="UTF-8"?><Root>';

        //档号
        $row = '<row SourceFieldName="dh" NewFieldName="档号" value="' . $data['dh'] . '"></row>';

        $xml = $xml . $row;
        //主题词
        $row = '<row SourceFieldName="ztc" NewFieldName="主题词" value="' . $data['ztc'] . '"></row>';

        $xml = $xml . $row;
        //密级
        $row = '<row SourceFieldName="mj" NewFieldName="密级" value="' . $data['mj'] . '"></row>';
        $xml = $xml . $row;
        //保管期限
        $row = '<row SourceFieldName="bgqx" NewFieldName="保管期限" value="' . $data['bgqx'] . '"></row>';
        $xml = $xml . $row;
        //全宗号
        $row = '<row SourceFieldName="qzh" NewFieldName="全宗号" value="' . $data['qzh'] . '"></row>';
        $xml = $xml . $row;
        //分类号
        $row = '<row SourceFieldName="flh" NewFieldName="分类号" value="' . $data['flh'] . '"></row>';
        $xml = $xml . $row;
        //案卷号
        $row = '<row SourceFieldName="ajh" NewFieldName="案卷号" value="' . $data['ajh'] . '"></row>';
        $xml = $xml . $row;
        //件号
        $row = '<row SourceFieldName="jh" NewFieldName="件号" value="' . $data['jh'] . '"></row>';
        $xml = $xml . $row;
        //关键词
        $row = '<row SourceFieldName="gjc" NewFieldName="关键词" value="' . $data['gjc'] . '"></row>';
        $xml = $xml . $row;
        //类别号
        $row = '<row SourceFieldName="lbh" NewFieldName="类别号" value="' . $data['lbh'] . '"></row>';
        $xml = $xml . $row;
        //文种
        $row = '<row SourceFieldName="wz" NewFieldName="文种" value="' . $data['wz'] . '"></row>';
        $xml = $xml . $row;
        //时间
        $row = '<row SourceFieldName="sj" NewFieldName="时间" value="' . $data['sj'] . '"></row>';
        $xml = $xml . $row;
        //题名
        $row = '<row SourceFieldName="tm" NewFieldName="题名" value="' . $data['tm'] . '"></row>';
        $xml = $xml . $row;
        //文件编号
        $row = '<row SourceFieldName="wjbh" NewFieldName="文件编号" value="' . $data['wjbh'] . '"></row>';
        $xml = $xml . $row;
        //载体类型
        $row = '<row SourceFieldName="ztlx" NewFieldName="载体类型" value="' . $data['ztlx'] . '"></row>';
        $xml = $xml . $row;
        //载体数量
        $row = '<row SourceFieldName="ztsl" NewFieldName="载体数量" value="' . $data['ztsl'] . '"></row>';
        $xml = $xml . $row;
        //载体单位
        $row = '<row SourceFieldName="ztdw" NewFieldName="载体单位" value="' . $data['ztdw'] . '"></row>';
        $xml = $xml . $row;
        //载体规格
        $row = '<row SourceFieldName="ztgg" NewFieldName="载体规格" value="' . $data['ztgg'] . '"></row>';
        $xml = $xml . $row;
        //责任者
        $row = '<row SourceFieldName="zrz" NewFieldName="责任者" value="' . $data['zrz'] . '"></row>';
        $xml = $xml . $row;
        //微缩号
        $row = '<row SourceFieldName="swh" NewFieldName="微缩号" value="' . $data['swh'] . '"></row>';
        $xml = $xml . $row;
        //档案馆号
        $row = '<row SourceFieldName="dagdh" NewFieldName="档案管号" value="' . $data['dagdh'] . '"></row>';
        $xml = $xml . $row;
        //数据类型
        $row = '<row SourceFieldName="sjlx" NewFieldName="数据类型" value="' . $data['sjlx'] . '"></row>';
        $xml = $xml . $row;
        //附注
        $row = '<row SourceFieldName="fz" NewFieldName="附注" value="' . $data['fz'] . '"></row>';
        $xml = $xml . $row;
        $xml = $xml . '</Root>';


        $result['data']['xml'] = $xml;


        $file_path=$data['file_path'];

        // Json 转成数组
        $file_path_arr=json_decode($file_path,true);

        $new_document_path="/" . $data['new_document_path'];
   

        // 获取 $new_document_path 的文件路径
        $new_document_path=dirname($new_document_path);
        // var_dump($new_document_path);

        $serverIp = config("kgFilePath");


        // 遍历数组
        foreach($file_path_arr as $key=>$value){
            // 获取文件名
            $file_path=$new_document_path. "/" . $value;
           
            $data['image_path'][]=  $serverIp  . $file_path;
        }

        //公章识别的图片
        $data['output_file']=   $serverIp  . $data['output_file'];
        //表单识别的图片
        // json 转成数组
        $mdArr=json_decode($data['md'],true);
        
        $data['mdArr']=$mdArr; 

 
       

        if (empty($result)) {
            return json(array('code' => 400, "data" => array(), 'message' => '请输入预览档案id'));
        } else {
            return json(array('code' => 200, "data" => $data, 'message' => '请输入预览档案id'));
        }
    }

    function getVlConfig()
    {
        $jh = Db::table('zstp_vl_conf')->where(array("id" => 1))->find();
        $tsc = Db::table('zstp_vl_conf')->where(array("id" => 2))->find();


        $result = array("jh" => $jh ['value'],
            "tsc" => $tsc ['value']
        );

        return json(array('code' => 200, "data" => $result, 'message' => '请输入预览档案id'));

    }


    function savevlconfig()
    {
        $data = request()->put();
        $value = $data['jh'];
        Db::table('zstp_vl_conf')->where(array("id" => 1))->update(array("value" => $value));
        Db::table('zstp_vl_conf')->where(array("id" => 2))->update(array("value" => $data['tsc']));


        return json(array('code' => 200, "data" => [], 'message' => '保存成功'));

    }


}